package com.boarsoft.boar.deploy.component;

import com.boarsoft.boar.deploy.entity.BuildPlan;
import com.boarsoft.boar.deploy.entity.BuildPlanItem;
import com.boarsoft.boar.deploy.plan.bean.BuildRequest;
import com.boarsoft.flow.core.bean.ProcessHandler;
import org.apache.maven.shared.invoker.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.Collections;

public class MvnInstallPH implements ProcessHandler {

	@Override
	public Object process(String entry, Object data, Throwable throwable) throws Throwable {
		BuildPlanItem bp=((BuildRequest)data).getCurPlanItem();
		String mvnPath=findMvnPath(bp.getPackPath());
		InvocationRequest request = new DefaultInvocationRequest();
		request.setPomFile(new File(mvnPath)); // 设置你的 Maven 项目的 pom.xml 文件路径
		request.setGoals(Collections.singletonList("clean install")); // 设置 Maven 目标
		Invoker invoker = new DefaultInvoker();
		invoker.setMavenHome(new File(System.getenv("MAVEN_HOME")));
		try {
			InvocationResult result = invoker.execute(request);
			if (result.getExitCode() != 0) {
				throw new IllegalStateException("Build failed.");
			}
		} catch (MavenInvocationException e) {
			e.printStackTrace();
		}
		//bp.setVer(findVersion(mvnPath));
		bp.setPackPath(mvnPath.replace("\\pom.xml",""));
		return data;
	}


	private String findMvnPath(String path){
		File dir=new File(path);
		if (dir == null || !dir.exists() || !dir.isDirectory()) {
			throw new RuntimeException("Directory not found or not a directory");
		}

		File[] files = dir.listFiles();
		if (files == null || files.length == 0) {
			throw new RuntimeException("Empty directory");
		}

		for (File file : files) {
			if(file.getName().equals("pom.xml")){
				return path;
			}
		}
		//当前目录没找到，就往下再找一层
		for (File file:files){
			if(file.isDirectory()){
				File[] fls = file.listFiles();
				for (File f : fls) {
					if(f.getName().endsWith("pom.xml")){
						return f.getAbsolutePath();
					}
				}
			}
		}
		throw new RuntimeException("cannot found pom file");
	}

	private String findVersion(String pomPath){
		try {
			// 创建一个 DocumentBuilder
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			// 解析 pom.xml 文件
			Document document = builder.parse(pomPath);

			// 获取版本号元素
			NodeList versionNodes = document.getElementsByTagName("version");
			if(versionNodes==null){
				versionNodes = document.getElementsByTagName("parent/version");
			}
			Element versionElement = (Element) versionNodes.item(0);
			return versionElement.getTextContent();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
